package com.uziot.bucket.scanlogin;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

/**
 * @author shidt
 * @version V1.0
 * @className Receiver
 * @date 2020-11-21 23:24:52
 * @description
 */
@Slf4j
public class Receiver {

    public static final String TOPIC_NAME = "login";
    /**
     * 存储登录状态
     */
    private final Map<String, CountDownLatch> loginMap = new ConcurrentHashMap<>();

    /**
     * 接收登录广播时会回调此方法
     *
     * @param loginId 用户ID
     */
    public void receiveLogin(String loginId) {

        if (loginMap.containsKey(loginId)) {
            CountDownLatch latch = loginMap.get(loginId);
            if (latch != null) {
                // 唤醒登录等待线程
                log.info("收到登陆成功loginId广播信息：[{}]", loginId);
                latch.countDown();
            }
        }
    }

    public CountDownLatch getLoginLatch(String loginId) {
        CountDownLatch latch;
        if (!loginMap.containsKey(loginId)) {
            latch = new CountDownLatch(1);
            loginMap.put(loginId, latch);
            log.info("新增线程计数器：[{}]", loginId);
        } else {
            latch = loginMap.get(loginId);
            log.info("获取线程计数器：[{}]", loginId);
        }
        return latch;
    }

    public void removeLoginLatch(String loginId) {
        loginMap.remove(loginId);
        log.info("移除线程计数器：[{}]", loginId);
    }
}
